import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import os from 'os'

// 获取本机IP地址
function getLocalIP() {
  const interfaces = os.networkInterfaces()
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      // 跳过非IPv4地址和回环地址
      if (iface.family !== 'IPv4' || iface.internal) continue
      return iface.address
    }
  }
  return '127.0.0.1'
}

const localIP = getLocalIP()

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  server: {
    proxy: {
      '/api': {
        target: `http://${localIP}:8080`,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    },
    open: true,
    host: '0.0.0.0',
    port: 5173,
    // 在服务器启动时显示IP地址
    configureServer(server) {
      server.httpServer?.once('listening', () => {
        const { port } = server.httpServer?.address() || { port: 5173 }
        console.log('\n')
        console.log('  🚀 开发服务器已启动')
        console.log('  --------------------')
        console.log(`  ➜  访问地址: http://${localIP}:${port}`)
        console.log('  --------------------\n')
      })
    }
  }
}) 